package day_2022_4_to_7.day48;

/**
 * 把字符串转换成整数
 * @author haomin
 * @date 2022/04/23 16:54
 **/
public class Day6_2_CharToInt {
    public int StrToInt(String str) {
        if(str == null || str.length() == 0){
            return 0;
        }
        char[] arr = str.toCharArray();
        int flag = 0;
        if(arr[0] == '-'){
            flag = 1;
        }

        int sum = 0;
        for (int i = flag; i < arr.length; i++) {
            if(arr[i] == '+'){
                // flag == 0,+号，进入下次循环
                continue;
            }
            if(arr[i] < 48 || arr[i] >57){
                // 遇到字符 return 0
                return 0;
            }
            sum = sum*10 + arr[i] - 48;
        }
        return flag == 0 ? sum : sum * -1;
    }
}